﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebVideo.Areas.Admin.Models;

namespace WebVideo.Areas.Admin.Controllers
{
    public class SupportAdminController : Controller
    {
        //
        // GET: /Admin/SupportAdmin/
        public ActionResult Index(string type)
        {
            dbVideoDataContext db = new dbVideoDataContext();
            if (type == "1")
            {
                return View(SupportAdminModel.LayDuLieu());
            }
            else
            {
               
                return View(db.EntitySupportAdmins.GroupBy(g=>g.UserName).Select(k=>k.First()).ToList());
            }
        }
        public ActionResult History(string UserName)
        {
            ViewBag.UserName = UserName;
            dbVideoDataContext db = new dbVideoDataContext();
            string  ad = db.EntityAdmins.First().UserName.ToString();
            return PartialView (db.EntitySupportAdmins.Where(g=>g.UserName == UserName || g.UserName == ad).ToList());
        }
        #region "Insert"
        public ActionResult Insert(string UserName,string Id)
        {
            SupportAdminModel tnew = new SupportAdminModel();
            tnew.UserName = UserName;
            return View(tnew);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Insert(SupportAdminModel Mtnew)
        {

            try
            {
                if (ModelState.IsValid)
                {
                    SupportAdminModel.Insert(Mtnew);
                    return RedirectToAction("Index", "SupportAdmin", new { type ="1" });
                }
            }
            catch
            {

                return RedirectToAction("Index", "Error", new { errorMsg = "Lỗi SQL hosting / server" });
            }
            return View(Mtnew);
        }
        #endregion //insert
        #region "Delete"
        public string Delete(int Id)
        {
            try
            {
                SupportAdminModel.Delete(Id);
                return "ok";
            }
            catch
            {
                return "error";

            }
        }
        #endregion //Delete

        public string  DeleteAll(string UserName)
        {
            dbVideoDataContext db = new dbVideoDataContext();
            try
            {
                  string  ad = db.EntityAdmins.First().UserName.ToString();
                  var q = db.EntitySupportAdmins.Where(g => (g.UserName == UserName || (g.UserName == ad && g.IdRoot == UserName)) && g.IdRoot != null).ToList();
                  db.EntitySupportAdmins.DeleteAllOnSubmit(q);
                  db.SubmitChanges();
                return "ok";
            }
            catch
            {
                return "error";
            }
        }

    }
}
